import configparser
import os
import pymysql
import traceback
class ConfigReader:
    def __init__(self,file):
        self.config = configparser.ConfigParser()  # 实例化ConfigParser对象
        config_path = os.path.split(os.path.realpath(__file__))[0] + os.sep + file
        self.config.read(config_path)   # 读取配置文件
    def get_Url(self,option):
        if self.config.has_section('URL'):  # 判断节在不在ini文件里面
            if self.config.has_option('URL',option):  # 判断这个选项在不在
                return self.config.get('URL',option)  # 在的话返回
            else:
                return None # 不在返回为空
        else:
            return None # 没有这个section，返回为空
    def get_option(self,option):
        sections = self.config.sections() # 获取所有的节
        for section in sections:
            if self.config.has_option(section,option):
                return self.config.get(section,option)
class DB:
    def __init__(self,database):
        self.database = database
        config = ConfigReader('dev_database.ini')
        """
        :param database: 要操作哪个数据库，传进来
        """
        self.user = config.get_option(database+"_user")  # root
        self.password = config.get_option(database+"_password")  # password
        self.host = config.get_option(database+"_host")  # host
    def connect(self):
        self.db = pymysql.connect(user=self.user,password=self.password,database=self.database,host=self.host,cursorclass =
        pymysql.cursors.DictCursor)
        self.cursor = self.db.cursor()
    def close(self):
        self.cursor.close()
        self.db.close()
    def searchOne(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchone()
            self.close()
            return result
        except Exception as e:
            self.db.rollback()
            traceback.print_exc()
            return result
    def searchall(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            self.close()
            return result
        except Exception as e:
            self.db.rollback()
            traceback.print_exc()
            return result
    def __edit(self,sql):
        self.connect()  # 先去连接数据库
        try:
            self.cursor.execute(sql)
            self.db.commit()  # 只要是对数据库产生了真实操作，就要做提交
            self.close()
        except Exception as e:
            self.db.rollback()
            traceback.print_exc()
    def insert(self,sql):
        self.__edit(sql)
    def delete(self,sql):
        self.__edit(sql)
    def update(self,sql):
        self.__edit(sql)


# if __name__ == '__main__':
#     d1 = DB('crmeb1')
#     # d1.connect()
#     print(d1.searchOne("select id from eb_user_group where group_name='赵霞'"))





















